﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Xml.Linq;
using UtfprLibrary.Exceptions;

namespace UtfprLibrary.Configurations.DesignTime {
    /// <summary>
    /// TODO
    /// </summary>
    public class ConnectionStringSection : UtfprSectionBase {
        /// <summary>
        /// TODO
        /// </summary>
        /// <exception cref="UtfprLibrary.Exceptions.UtfprConfigurationsException">Thrown when an exception occurs.</exception>
        public ConnectionStringElement[] ConnectionStrings {
            get {
                try {
                    XDocument config = GetAppConfigDocument();

                    var connectionStrings = config.Root.Elements().Where(e => e.Name.LocalName == "connectionStrings").FirstOrDefault();
                    if (connectionStrings == null) { throw new Exception("Tag connectionStrings não encontrada."); }

                    var adds = connectionStrings.Elements().Where(e => e.Name.LocalName == "add").ToList();
                    if (adds.Count == 0) { throw new Exception("Tag add não encontrada."); }

                    var connStrElements = new List<ConnectionStringElement>();
                    foreach (var add in adds) {
                        var name = add.Attributes().Where(e => e.Name.LocalName == "name").FirstOrDefault();
                        var connectionString = add.Attributes().Where(e => e.Name.LocalName == "connectionString").FirstOrDefault();
                        var providerName = add.Attributes().Where(e => e.Name.LocalName == "providerName").FirstOrDefault();

                        if (name != null && connectionString != null && providerName != null) {
                            connStrElements.Add(new ConnectionStringElement(name.Value, connectionString.Value, providerName.Value));
                        }
                    }

                    return connStrElements.ToArray();
                } catch (Exception ex) {
                    throw new UtfprConfigurationsException(Properties.Resources.Configurations_DesignTime_UtfprSection_ExMsg_ConnectionStrings, ex);
                }
            }
        }
    }
}
